﻿using B.S.Data.MES.API.Applications.AccountApplication.Command;
using B.S.Domain.Accounts;
using B.S.Infratrctrue;
using B.S.Requst;
using MD5Hash;
using MediatR;
using System.Transactions;

namespace B.S.Data.MES.API.Applications.AccountApplication.CommandHandler
{
    public class AccountCreateCommandHandler : IRequestHandler<AccountCreateCommand, APIRequst<int>>
    {
        public AccountCreateCommandHandler(IBaseRepository<Account> accountRepository,IBaseRepository<UserRole> roleRepository)
        {
            AccountRepository = accountRepository;
            RoleRepository = roleRepository;
        }

        public IBaseRepository<Account> AccountRepository { get; }
        public IBaseRepository<UserRole> RoleRepository { get; }

        public async Task<APIRequst<int>> Handle(AccountCreateCommand request, CancellationToken cancellationToken)
        {
            using (var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    #region 用户新增
                    request.Data.CreateName = "管理员";
                    request.Data.CreateTime = DateTime.Now;
                    request.Data.UserPass = request.Data.UserPass.GetMD5().ToUpper();
                    request.Data.isDel = false;
                   await AccountRepository.Add(request.Data);
                    #endregion
                    #region 用户角色新增
                    request.RoleData.UserId = request.Data.UserId;
                    request.RoleData.RoleId = request.RoleData.RoleId;
                    await RoleRepository.Add(request.RoleData);
                    #endregion
                    tran.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
            }

            return new APIRequst<int>
            {
                Code = RequstCode.成功,
                Msg = "",
                Data = 1
            };
        }
    }
}
